<!--
 * @Description: mbti性格测试
 * @Author: ZhangHan
 * @Date: 2025-09-10 14:15:28
 * @LastEditTime: 2025-09-15 17:40:53
 * @LastEditors: ZhangHan
-->
<template>
  <view class="mbti">
    <!-- 内容区域 -->
    <view class="content">
      <view class="title">MBTI性格测试</view>
      <view class="tit_desc"
        >这个测试包含20个问题，将帮助你确定自己的MBTI人格类型。请根据你的真实情况和第一反应进行选择。</view
      >
      <view class="tit_tag">
        <view class="tag_item">
          <uni-icons
            type="notification"
            color="purple"
            class="icon"
          ></uni-icons>
          约10分钟完成
        </view>
        <view class="tag_item">
          <uni-icons type="help" color="purple" class="icon"></uni-icons
          >20个问题
        </view>
        <view class="tag_item">
          <uni-icons type="folder-add" color="purple" class="icon"></uni-icons
          >详细分析
        </view>
      </view>
      <view class="startbtn" v-if="lastInfo" @click="reset">{{
        "重新测试"
      }}</view>
      <view class="progressText" v-if="!lastInfo">
        <view class="text">进度</view>
        <view class="percent">{{ step + 1 }}/20</view>
      </view>
      <progress
        backgroundColor="#ffffff"
        activeColor="#8e2de2"
        border-radius="20px"
        :percent="percentNum"
        stroke-width="15px"
        v-if="!lastInfo"
      />
      <view class="quesCard" v-if="!lastInfo">
        <view class="q_head">问题 {{ step + 1 }}/20 </view>
        <view class="q_text"
          >{{ `${step + 1}、` }} {{ questions[step]?.text }}
        </view>
        <uni-data-checkbox
          wrap
          selectedColor="#8e2de2"
          selectedTextColor="#8e2de2"
          mode="button"
          v-model="formData[`value${step + 1}`]"
          :localdata="questions[step].options"
        ></uni-data-checkbox>
      </view>
      <view class="btn_group" v-if="!lastInfo">
        <view
          @click="prev"
          :class="['prevBtn', btnGroup.loading1 ? 'btn_active' : '']"
          >上一题</view
        >
        <view
          :class="['nextBtn', btnGroup.loading2 ? 'btn_active' : '']"
          @click="next"
        >
          {{ step + 1 === 20 ? "完成测试" : "下一题" }}
        </view>
      </view>
      <!-- 结果卡片 -->
      <view class="resultCard" v-if="lastInfo">
        <view class="r_head">
          <view>你的MBTI性格类型是</view>
          <view class="boldtext">{{ lastInfo?.type }}</view>
          <view>{{ lastInfo?.name }}</view>
        </view>
        <view class="r_main">
          <view class="r_one">
            <view class="left">
              <view class="rl_title"> 关于你的性格 </view>
              <view class="rl_textArea">{{ lastInfo?.description }}</view>
            </view>
            <view class="right">
              <view class="rr_title"> 你的优势 </view>
              <view class="rr_list">
                <view
                  class="rrl_item"
                  :key="item"
                  v-for="item in lastInfo?.strengths"
                >
                  <uni-icons
                    class="check"
                    color="#22BE8B"
                    type="checkmarkempty"
                  ></uni-icons>
                  {{ item }}
                </view>
              </view>
            </view>
          </view>
          <view class="emotion_tags">
            <view class="e_title">你的性格标签</view>
            <view class="tag_group">
              <view
                class="tag_item"
                :key="item"
                v-for="item in lastInfo?.tags"
                >{{ item }}</view
              >
            </view>
          </view>
          <view class="suggest">
            <view class="s_title">给你的搞笑小建议</view>
            <view class="s_content">
              {{ lastInfo.funnyAdvice }}
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="water-drop" />
    <view class="water-drop wd2" />
    <ConfettiOvlay ref="confettiRef" />
  </view>
</template>

<script setup lang="ts">
import { reactive, ref, computed } from "vue";
import { questions, personalityTypes } from "./dataSource";
import ConfettiOvlay from "./components/ConfettiOvlay.vue";

const step = ref(0);
const confettiRef = ref<any>(null);

const formData = reactive<any>({});
const btnGroup = reactive({
  loading1: false,
  loading2: true,
});

const resultInfo = reactive<any>({
  currentQuestion: 0,
  answers: {},
  results: {
    EI: 0,
    SN: 0,
    TF: 0,
    JP: 0,
  },
});

const lastInfo = ref<any>();

const percentNum = computed(() => {
  return (step.value + 1) * 5 === 100 ? 100 : (step.value + 1) * 5;
});

// 小程序中，uniapp的ref要绑定在子组件中才能被获取，如果绑定在view，是获取不了的，你得把业务写在一个组件来引用才行。h5则没有这种情况。

// 首先确保在 next 函数中正确保存答案
const next = () => {
  btnLoading2();

  // 保存当前答案
  if (formData[`value${step.value + 1}`] !== undefined) {
    resultInfo.answers[step.value] = formData[`value${step.value + 1}`];
  }

  if (step.value === 19) {
    uni.showToast({
      title: "没有下一题了",
      icon: "error",
      mask: true,
      duration: 1000,
    });
    displayResult();
    return;
  }

  if (formData[`value${step.value + 1}`] == undefined) {
    uni.showToast({
      title: "请选择完毕",
      icon: "error",
      mask: true,
      duration: 1000,
    });
    return;
  }

  step.value += 1;
};

// 修改 calculateResult 函数
function calculateResult() {
  // 重置结果
  resultInfo.results = {
    EI: 0,
    SN: 0,
    TF: 0,
    JP: 0,
  };

  // 确保所有答案都已保存
  for (let i = 0; i < 20; i++) {
    if (formData[`value${i + 1}`] !== undefined) {
      resultInfo.answers[i] = formData[`value${i + 1}`];
    }
  }

  // 打印答案用于调试
  console.log("所有答案:", resultInfo.answers);

  // 计算每个维度的得分
  for (let i = 0; i < questions.length; i++) {
    const question = questions[i];
    const answer = resultInfo.answers[i];

    if (answer !== undefined) {
      // 注意：这里使用 answer 作为索引获取 question.value 数组中的值
      resultInfo.results[question.dimension] += question.value[answer];
      console.log(
        `问题${i + 1}, 维度: ${question.dimension}, 答案: ${answer}, 得分: ${
          question.value[answer]
        }`
      );
    }
  }

  // 打印各维度得分用于调试
  console.log("各维度得分:", resultInfo.results);

  // 确定每个维度的倾向
  const EIType = resultInfo.results.EI >= 2 ? "E" : "I"; // EI维度有5个问题，所以>=2表示E倾向
  const SNType = resultInfo.results.SN >= 2 ? "S" : "N"; // SN维度有5个问题，所以>=2表示S倾向
  const TFType = resultInfo.results.TF >= 2 ? "T" : "F"; // TF维度有5个问题，所以>=2表示T倾向
  const JPType = resultInfo.results.JP >= 2 ? "J" : "P"; // JP维度有5个问题，所以>=2表示J倾向

  const mbtiType = EIType + SNType + TFType + JPType;
  console.log("计算出的MBTI类型:", mbtiType);

  return mbtiType;
}

//上一步
const prev = () => {
  btnLoading1();
  if (step.value === 0) {
    uni.showToast({
      title: "没有上一题了",
      icon: "error",
      mask: true,
      duration: 1000,
    });
    return;
  }

  step.value -= 1;
};

function btnLoading1() {
  btnGroup.loading1 = true;

  setTimeout(() => {
    btnGroup.loading1 = false;
  }, 300);
}

function btnLoading2() {
  btnGroup.loading2 = true;

  setTimeout(() => {
    btnGroup.loading2 = false;
  }, 300);
}

// 显示测试结果
function displayResult() {
  uni.showLoading({
    title: "生成中",
  });
  setTimeout(() => {
    const type = calculateResult();
    console.log("🚀 ~ displayResult ~ type:", type);
    const personality = personalityTypes[type];
    console.log(personality);
    lastInfo.value = personality;
    lastInfo.value.type = type;
    uni.hideLoading();
    confettiRef.value?.createConfetti();
    Object.keys(formData).forEach((key) => {
      formData[key] = undefined;
    });
    step.value = 0;
  }, 1500);
}

//重新测试
const reset = () => {
  step.value = 0;
  lastInfo.value = null;
  // formData = {};
  Object.keys(formData).forEach((key) => {
    formData[key] = undefined;
  });
};
</script>

<style scoped lang="scss">
@use "./index.scss";
</style>
